import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import userRoutes from './routes/user.route';
import roleRoutes from './routes/role.route';
import permissionRoutes from './routes/permission.route';
import categoryRoutes from './routes/category.route';
import productRoutes from './routes/product.route';
import addressRoutes from './routes/address.route';
import orderRoutes from './routes/order.route';
import authRoutes from './routes/auth.route'; // 引入认证路由
import { swaggerUI } from './config/swagger';
import { initDatabase } from './config/db';
import dotenv from 'dotenv';
import errorHandler from './middleware/errorMiddleware';
import cors from 'koa-cors'; // 引入跨域中间件

dotenv.config();
const app = new Koa();

app.use(bodyParser());
app.use(errorHandler); // 全局错误处理
app.use(swaggerUI); // 确保 Swagger UI 在身份验证中间件之前
app.use(cors({origin: '*', credentials: true})); // 添加跨域支持
app.use(authRoutes.routes()).use(authRoutes.allowedMethods()); // 不需要身份验证的路由
app.use(userRoutes.routes()).use(userRoutes.allowedMethods());
app.use(roleRoutes.routes()).use(roleRoutes.allowedMethods());
app.use(permissionRoutes.routes()).use(permissionRoutes.allowedMethods());
app.use(categoryRoutes.routes()).use(categoryRoutes.allowedMethods());
app.use(productRoutes.routes()).use(productRoutes.allowedMethods());
app.use(addressRoutes.routes()).use(addressRoutes.allowedMethods());
app.use(orderRoutes.routes()).use(orderRoutes.allowedMethods());

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`服务器正在 http://localhost:${port} 运行`);
  console.log(`Swagger 可以在 http://localhost:${port}/docs 访问`);
});

async function startApp() {
  try {
    await initDatabase();
    console.log('数据库同步完成');
  } catch (error) {
    console.error('数据库同步失败:', error);
  }
}

startApp();
